package com.silong.swing.myWindows;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by 龙哥 on 2022-01-17 15:38
 * Silong Software.
 */

public class TreeFrame extends JFrame {

    JTree familyTree;
    JScrollPane jspFamily;

    JButton button1;
    JButton button2;

    public TreeFrame(){
        init();
    }

    private void init(){

        //创建根节点
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("曹操");
        //创建子节点
        DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("曹植");
        DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("曹丕");
        DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("曹彰");
        DefaultMutableTreeNode a4 = new DefaultMutableTreeNode("曹昴");
        //创建父子关系，添加的顺序就是按 add 顺序来的
        root.add(a1);
        root.add(a2);
        root.add(a3);
        root.add(a4);
        DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("曹睿");
        DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("曹霖");
        DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("曹志");
        a2.add(b1);
        a2.add(b2);
        a4.add(b3);
        DefaultMutableTreeNode d1 = new DefaultMutableTreeNode("曹芳");
        b3.add(d1);
        familyTree = new JTree(root);
        //将树放到滚动条中
        jspFamily = new JScrollPane(familyTree);

        button1 = new JButton("按钮一");
        button2 = new JButton("退出");

        Container window = this.getContentPane();
        this.setSize(800, 600);
        this.setLocationRelativeTo(null); //距中
        this.setTitle("自定义控件大小位置");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //退出窗口关闭程序
        //设置布局为空，优点:摆放灵活，缺点：代码量大，自适应能力差。
        this.setLayout(null);

        jspFamily.setLocation(50,50);
        jspFamily.setSize(300,400);
        familyTree.setFont(new Font("宋体", Font.BOLD, 25));

        //自定义按钮的位置 ，大小
        button1.setLocation(550,50); //设置按钮位置
        button1.setSize(100,50); //设置按钮大小
        button1.setFont(new Font("黑体", Font.BOLD, 20));

        button2.setFont(new Font("黑体", Font.BOLD, 20));
        button2.setBounds(400, 50, 100, 50); //一次性设置位置与大小
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        window.add(button1);
        window.add(button2);
        window.add(jspFamily);

    }

    public static void main(String[] args) {
        TreeFrame myFrame = new TreeFrame();
        myFrame.setVisible(true);
    }
}
